package com.listener.dao.impl;

import com.listener.dao.MoveDao;
import com.listener.pojo.Move;
import com.listener.pojo.Move;
import com.listener.pojo.Page;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Repository
public class MoveDaoImpl implements MoveDao {
    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate=jdbcTemplate;
    }

    public List<Move> selectAllMove() {
        String sql="select * from move";
        RowMapper<Move> rowMapper = new BeanPropertyRowMapper<Move>(Move.class);
        return this.jdbcTemplate.query(sql, rowMapper);
    }

    public List<Map<String, Object>> selectAllCategory() {
        String sql="select category from move GROUP BY category";
        return this.jdbcTemplate.queryForList(sql);
    }

    public Page<Move> selectMovePage(Move move, Integer pageNum, Integer pageSize) {
        Page<Move> page=new Page<Move>();
        String sql=" SELECT CEIL(COUNT(*) / ?) as pageSum FROM move  where 1=1 ";
        sql = getString(move, sql);
        RowMapper<Move> rowMapper = new BeanPropertyRowMapper<Move>(Move.class);
        page.setPageSum(Integer.parseInt(this.jdbcTemplate.queryForMap(
                sql,new Object[]{pageSize}).get("pageSum").toString()));
        page.setPageNum(pageNum);
        page.setPageSize(pageSize);
        sql="select * from move where 1=1 ";
        sql = getString(move, sql);
        sql+=" limit "+(pageNum-1)*pageSize+","+pageSize;
        page.setPage(this.jdbcTemplate.query(sql,rowMapper));
        return page;
    }

    private String getString(Move move, String sql) {
        if(move.getMove()!=null){
            sql+="and move like CONCAT('%"+move.getMove()+"%') ";
        }
        if(move.getType()!=null){
            sql+="and type='"+move.getType()+"' ";
        }
        if(move.getCategory()!=null){
            sql+="and category='"+move.getCategory()+"' ";
        }
        if(move.getDescription()!=null){
            sql+="and description like CONCAT('%"+move.getDescription()+"%') ";
        }
        return sql;
    }

    public List<Move> selectMove(Move move) {
        RowMapper<Move> rowMapper = new BeanPropertyRowMapper<Move>(Move.class);
        String sql="select * from move where 1=1 ";
        if(move.getMove()!=null){
            sql+="and move='"+move.getMove()+"'";
        }
        return this.jdbcTemplate.query(sql,rowMapper);
    }
}
